<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Getters</title>
        <script src="https://unpkg.com/vue@next"></script>
        <script src="https://unpkg.com/vuex@next"></script>
    </head>
    <body>

        <div id="app">
            <h3>{{title}}</h3>
            <div v-for="(book , index ) in bookList" :key="book.id">
                {{index+1}} , {{book.name}} , {{book.price}} , {{book.discount}}
            </div>
            <div>{{single}}</div>
        </div>

        <script>
            const store = Vuex.createStore({
                state () {
                    return {
                        books: [
                            { id: 1234 , name: 'Vue从入门到入坟' , price: 99.8 , discount: 0.5 } ,
                            { id: 4321 , name: '上课睡觉是如何练成的' , price: 55 , discount: 0.5 } ,
                            { id: 5678 , name: '1天精通HTML和CSS' , price: 18 , discount: 1 }
                        ]
                    }
                },
                getters: {
                    list: state => state.books.filter( book => book.price > 50 ),
                    getBookById: state => id => state.books.find( b => b.id = id )
                }
            });

            const app = Vue.createApp({
                data(){
                    return { title: '图书列表' }
                },
                computed: {
                    bookList(){ 
                        // 注意这里使用的是 在 store 中的 getters 中定义的 list 函数的返回值
                        console.log( this.$store.getters.list );
                        return this.$store.getters.list ;
                    },
                    single(){
                        // 注意这里使用的是 在 store 中的 getters 中定义的 getBookById 函数的返回值
                        console.log( this.$store.getters.getBookById );
                        return this.$store.getters.getBookById(1234) ;
                    }
                }
            });

            app.use( store );

            app.mount( "#app" );
        </script>
        
    </body>
</html>